package com.ruipeng.shengyapo.service.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruipeng.shengyapo.dao.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruipeng.shengyapo.service.LockService;
import com.ruipeng.shengyapo.utils.HttpUtils;
import com.ruipeng.shengyapo.utils.YunBa;

@Service
public class LockServiceImpl implements LockService {

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private CouponMapper couponMapper;

	@Autowired
	private BikeMapper bikeMapper;

	@Override
	public int lock(String key) {
		return 0;
	}

	@Override
	public Map<String, Object> getRecentOrderByIMEI(Map<String, Object> params) {
		Map<String, Object> orderData = orderMapper.getRecentOrderByIMEI(params);
		return orderData;
	}

	@Override
	public Map<String, Object> getRecentOrderIsSetEndPath(Map<String, Object> params) {
		Map<String, Object> orderData = orderMapper.getRecentOrderByIMEI(params);
		return orderData;
	}

	@Override
	public List<Map<String, Object>> closeLock(Map<String, Object> params) {
		System.out.println("closeLock Service: params: " + params);
		
		// 更新自行车（锁）状态
		Map<String, Object> bikeParams = new HashMap<String, Object>();
		bikeParams.put("lockState", "0");
		bikeParams.put("imei", params.get("imei"));
		bikeMapper.updateBikeStatusByImei(bikeParams);
		
		// 获取最近订单
		Map<String, Object> orderData = orderMapper.getRecentOrderByIMEI(params);
		System.out.println("orderData: " + orderData);
		Integer riding_status = 1;
		if (orderData != null) {
			riding_status = (Integer) orderData.get("riding_status");
		}
		
		if (riding_status == 0) { // 订单未完成
			Date endTime = new Date();
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
			Date startTime = null;
			try {
				startTime = format.parse((String) orderData.get("order_createtime"));
			} catch (ParseException e) {
				e.printStackTrace();
			}

			System.out.println("endTime: " + endTime.getTime() + "  createTime: " + startTime.getTime());
			System.out.println("deltaTime: " + (endTime.getTime() - startTime.getTime()));
			double riding_time = (endTime.getTime() - startTime.getTime()) / 1000; // 骑行时常（秒）
			System.out.println("ridingTime: " + riding_time);
			long riding_unit = (long) Math.ceil((double)riding_time / 60 / 30); // 多少个30分钟
			System.out.println("riding_unit: " + riding_unit);
			double riding_cost = 0.5 * riding_unit; // 骑行费用（元）
			riding_cost = riding_cost > 2 ? 2 : riding_cost; // 最多2元
			System.out.println("riding_cost: " + riding_cost);

			// 构建订单对象
			Map<String, Object> orderParams = new HashMap<String, Object>();
			// 用户id
			Integer userId = (Integer) orderData.get("user_id");
			// 获取优惠券列表
			List<Map<String, Object>> couponList = couponMapper.getCouponListByUserId(userId);

            double couponMoney = 0;
			if (couponList.size() > 0) {
				// 使用优惠券
				orderParams.put("coupon_no", couponList.get(0).get("couponNo"));
				// 更改优惠券状态
				String couponNo = couponList.get(0).get("couponNo").toString();
				System.out.println("优惠劵: " + couponNo + " 已使用");
				couponMapper.updateCouponByCouponNo(couponNo);
				// 获取优惠券金额
                couponMoney = Double.parseDouble(couponList.get(0).get("couponMoney").toString());
				// 当本次骑行订单金额大于优惠券金额
				if (riding_cost > couponMoney) {
					riding_cost = riding_cost - couponMoney;

					// 查询用户余额
					Map<String, Object> userSearchParams = new HashMap<String, Object>();
					userSearchParams.put("user_id", userId);
					Map<String, Object> accountData = userMapper.getUserAccount(userSearchParams);

					/// 扣除用户余额并更新表
					setUserAccount(accountData, riding_cost, userId);
				}

			} else {
				// 查询用户余额
				Map<String, Object> userSearchParams = new HashMap<String, Object>();
				userSearchParams.put("user_id", userId);
				Map<String, Object> accountData = userMapper.getUserAccount(userSearchParams);
				
				// 扣除用户余额并更新表
				setUserAccount(accountData, riding_cost, userId);
			}

			// 更新订单
            orderParams.put("coupon_cost", couponMoney);//优惠卷金额
			orderParams.put("order_endtime", endTime);
			orderParams.put("riding_time", riding_time);
			orderParams.put("riding_cost", riding_cost);
			orderParams.put("riding_order_id", orderData.get("riding_order_id"));
			orderMapper.completeOrder(orderParams);
			System.out.println("更新订单：" + orderData.get("riding_order_id") + " 状态改为已完成");
			
			// 向客户端发通知
			String tsStr = YunBa.yunbaUtil();
			tsStr = tsStr.replace("#topic", "Topic_User_" + userId);
			tsStr = tsStr.replace("#alert",
					"自行车" + params.get("imei") + "骑行已结束！&" + (Integer) orderData.get("riding_order_id") + "&");
			tsStr = tsStr.replace("#type", "1");
			HttpUtils.sendPost(YunBa.url, tsStr.toString());
			System.out.println("云吧推送参数: " + tsStr);
		}
		return null;
	}
	
	// 扣除用户余额
	private void setUserAccount (Map<String, Object> accountData, double riding_cost, Integer userId) {
		BigDecimal account = (BigDecimal) accountData.get("user_account");
		BigDecimal result = account.subtract(new BigDecimal(riding_cost));
		Map<String, Object> userAccountParams = new HashMap<String, Object>();
		userAccountParams.put("userId", userId);
		userAccountParams.put("user_account", result.doubleValue());
		userMapper.setUserAccount(userAccountParams);
	}

	@Override
	public int setRecentOrderEndPath(Map<String, Object> params) {
		Map<String, Object> orderData = orderMapper.getRecentOrderByIMEI(params);

		Map<String, Object> pathData = new HashMap<String, Object>();
		pathData.put("riding_order_id", orderData.get("riding_order_id"));
		pathData.put("location", params.get("location"));

		return orderMapper.setRecentOrderEndPath(pathData);
	}

	@Override
	public int updateBikeLocation(Map<String, Object> params) {
		return bikeMapper.updateBikeLocation(params);
	}

    @Override
    public int updateBikeState(Map<String, Object> params) {

	    bikeMapper.updateBikeStatusByImei(params);

        return 0;
    }
}
